package anshe.net
{
	import anshe.event.AnsheNetEvent;
	
	import flash.events.EventDispatcher;
	import flash.events.SyncEvent;
	import flash.net.NetConnection;
	import flash.net.SharedObject;

	public dynamic class RedSharedObject extends EventDispatcher
	{
		private static var m_so:RedSharedObject;
		public static function getSO():RedSharedObject
		{
			if(!m_so)
			{
				m_so = new RedSharedObject();
			}
			return m_so;
		}
		
		private var soName:String;		//	SharedObject 名称
		private var so:SharedObject;	//	SharedObject 对象
		
		private var soConnected:Boolean	= false;	//	SharedObject 是否已经连接
		
		public function get connected():Boolean
		{
			return soConnected;
		}
		
		//	连接服务器端的 SharedObject 对象
		//		p_soName		SharedObject 名称
		//		p_nc			Red5 连接对象
		//		p_persistant	SharedObject 是否永远存放（默认值为false）
		public function connect(p_soName:String, p_nc:NetConnection, p_persistant:Boolean = false):void
		{
			var nc:RedConnection = p_nc as RedConnection;
			
			soName = p_soName;
			
			// 连接到远程服务器上面的 SharedObject
			so = SharedObject.getRemote(p_soName, nc.uri, p_persistant);
			
			red5soInit();
			
			// 侦听 SharedObject 的更新事件
			so.addEventListener(SyncEvent.SYNC,onStatus);
			// so.addEventListener(NetStatusEvent.NET_STATUS, onSoConnStatue);
			
			// 开始连接服务器
			so.connect(nc);
		}
		
		//	关闭 SharedObject 连接
		public function close():void
		{
			so.close();
		}
		
		//	为 SharedObject 注册侦听器
		public function set client(obj:*):void
		{
			so.client = obj;
		}

		//---------------------------------------------------------------------------
		
		//	初始化 SharedObject 客户端为本地
		private function red5soInit():void
		{
			so.client = new Object();
			so.client.serverSystemBroadcast = onServerSystemBroadcast;
			so.client.serverReturn = serverReturn;
			so.client.serverLog = serverLog;
		}
		
		//	SharedObject 全局广播事件
		private function onServerSystemBroadcast():void	
		{
			dispatchEvent(new AnsheNetEvent(AnsheNetEvent.SO_BROADCAST, arguments));
		}
		
		//	SharedObject 消息事件
		private function serverReturn():void
		{
		    dispatchEvent(new AnsheNetEvent(AnsheNetEvent.SO_MESSAGE, arguments));
		}
		
		//	服务器异常状态
		private function serverLog():void
		{
			dispatchEvent(new AnsheNetEvent(AnsheNetEvent.SO_STATUE, arguments));
		}
		
		// 收到 SharedObject 更新后触发事件（向外抛出事件
		private function onStatus(e:SyncEvent):void
		{
			soConnected = true;
			dispatchEvent(new AnsheNetEvent(AnsheNetEvent.SO_RUSH_DATA, e));
		}
		
	}
}